package com.pinyou.user.service;

import com.jzfai.user.pojo.User;
import com.pinyou.common.utils.CodecUtils;
import com.pinyou.common.utils.NumberUtils;
import com.pinyou.user.mapper.UserMapper;
import lombok.extern.java.Log;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Log
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    static final String KEY_PREFIX ="user:code:phone:";

    public Boolean checkData(String data, Integer type) {
        User user = new User();
        switch (type){
            case 1:
                user.setUsername(data);
                break;
            case 2:
                user.setPhone(data);
                break;
            default:
                return null;
        }
        return this.userMapper.selectCount(user) == 0;
    }
    public Boolean sendVerifyCode(String phone) {
        // 生成验证码
        String code = NumberUtils.generateCode(6);
        Map<String, String> msg = new HashMap<>();
        msg.put("phone",phone);
        msg.put("code",code);
        // 发送短信
        this.amqpTemplate.convertAndSend("pinyou.sms.exchange", "sms.verify.code",msg);
        // 将code存入redis
        this.redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5, TimeUnit.MINUTES);
        return true;
    }
    public Boolean register(@Valid User user, String code) {
        // 校验短信验证码
        String cacheCode = this.redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if(!StringUtils.equals(code,cacheCode)){
            return false;
        }
        // 生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        // 对密码加密
        user.setPassword(CodecUtils.md5Hex(user.getPassword(),salt));
        // 强制设置不能指定的参数为null
        user.setId(null);
        user.setCreated(new Date());
        // 添加到数据库
        boolean b=this.userMapper.insertSelective(user) == 1;
        // 注册成功，删除redis中的记录
        if(b){
           this.redisTemplate.delete(KEY_PREFIX+user.getPhone());
        }
        return b;
    }
    public User queryUser(String username, String password) {
        // 查询
        User recode = new User();
        recode.setUsername(username);
        User user = this.userMapper.selectOne(recode);
        // 校验用户名
        if(user == null){
            return null;
        }
        // 校验密码
        if(!user.getPassword().equals(CodecUtils.md5Hex(password,user.getSalt()))){
           return null;
        }
        // 用户名密码都正确
        return user;
    }
}